import subprocess
import os

def excute_shell(command, path=None, pipe_out=True):
    """
    执行shell脚本
    :param command: 命令行
    :param path: 执行命令行时所在路径，默认当前路径
    :return:
    """
    stderr, stdout = (None, None)
    if pipe_out:
        stderr, stdout = (subprocess.PIPE, subprocess.PIPE)
    result = subprocess.run(command, shell=True, stderr=stderr, stdout=stdout, text=True, cwd=path)
    desc = result.stdout
    if result.returncode != 0:
        desc = result.stderr
    print("python日志 \n执行脚本命令: %s  \n结果: %s" % (command, desc))
    return (result.returncode, desc)

def git_branch_current(git_path, **keywords):
    """
    :param git_path: git项目路径
    :param keywords: 其余参数
    :return: 所在分支
    """
    command = "git branch"
    code, desc = excute_shell(command, path=git_path)
    if code != 0:
        print("python日志 获取git当前分支错误")
        return None
    for s in desc.split("\n"):
        if "*" in s:
            s = s.replace(" ", "")
            s = s.replace("*", "")
            return s

def git_branch_exist(git_path, branch, **keywords):
    """
    判断git分支是否存在
    :param git_path:
    :param branch:
    :param keywords:
    :return:
    """
    command = "git branch"
    code, desc = excute_shell(command, path=git_path)
    if code != 0:
        print("python日志 判断gif分支是否存在错误")
        return None
    for s in desc.split("\n"):
        s = s.replace(" ", "")
        s = s.replace("*", "")
        if s == branch:
            return True
    return False

def git_branch_switch(git_path, branch, **keywords):
    """
    切到到指定分支
    :param git_path:
    :param branch:
    :param keywords:
    :return:
    """
    current = git_branch_current(git_path)
    if current == branch:
        print("paython日志 当前已经在 %s 分支" % branch)
        return
    command = "git checkout -b " + branch
    if git_branch_exist(git_path, branch):
        command = "git checkout " + branch
    code, desc = excute_shell(command, path=git_path)
    if code != 0:
        print("python日志 切换git分支错误")

def git_clone(git_path, branch, remote_url, item_name, **keywords):
    """
    克隆项目
    :param git_path:
    :param branch:
    :param remote_url:
    :param item_name:
    :param keywords:
    :return:
    """
    command = "git clone -b %s %s %s" % (branch, remote_url, item_name)
    code, desc = excute_shell(command, path=git_path)
    if code != 0:
        print("python日志 git clone错误")
    command = "git branch --set-upstream-to=origin/%s %s" % (branch, branch)
    code, desc = excute_shell(command)
    if code != 0:
        print("python日志 git branch --set-upstream错误")

def git_pull(git_path, **keywords):
    """
    同步当前分支代码
    :param git_path:
    :return:
    """
    if not os.path.exists(git_path):
        print("python日志 git pull 本地项目不存在")
        return
    command = "git pull"
    code, desc = excute_shell(command, path=git_path)
    if code != 0:
        print("python日志 git pull错误")
